<?php



namespace App\Http\Controllers\Backend;
use  App\Http\Requests\Company\RoleRequest;
use App\Services\Business\Models\Appraise;
use App\Services\Member\Models\Role;
use App\Services\Member\Models\UserRole;
use App\Services\Member\Models\User;
use App\Services\Member\Models\UserRemark;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Constant\ApiV2Constant;
use App\Services\Member\Services\RoleService;
use App\Services\Member\Interfaces\RoleServiceInterface;



class RoleController extends BaseController
{

    /**
     * @var RoleService
     */
    protected $roleService;


    public function __construct(
        RoleServiceInterface $roleService

    ) {
        $this->roleService = $roleService;

    }

    /**
     * @api {get} /api/v2/roles VIP会员列表
     * @apiGroup VIP
     * @apiVersion v2.0.0
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object[]} data 数据
     * @apiSuccess {Number} data.id VIPid
     * @apiSuccess {String} data.name VIP名
     * @apiSuccess {Number} data.charge 价格
     * @apiSuccess {Number} data.expire_days 有效天数
     * @apiSuccess {String[]} data.desc_rows 描述
     */
    public function index()
    {

        $companyId = $this->loginCompanyId();
        $roles =   Role::query()->where('company_id',$companyId)->get()->toArray();

        return $this->successData(compact('roles'));
    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function members(Request $request)
    {
        // 过滤条件
        $companyId = $this->loginCompanyId();
        $keywords = $request->input('keywords', '');
        $roleId = $request->input('role_id');
        $isAppraised = $request->input('is_appraised');
        $createdAt = $request->input('created_at');

        // 排序字段
        $sort = $request->input('sort', 'id');
        $order = $request->input('order', 'desc');

        $members = UserRole::query()
            ->with(['user:id,nick_name,avatar,uuid'])
            ->when($keywords, function ($query) use ($keywords) {
                $userIds = User::query()->where('nick_name', 'like', '%' . $keywords . '%')
                    ->orWhere('mobile', $keywords)
                    ->orWhere('uuid', $keywords)->select('id')->get()->pluck('id')->toArray();
                $query->whereIn('user_id',$userIds);

            })
            ->when($roleId, function ($query) use ($roleId) {

                $query->where('role_id', $roleId);
            })
            ->when($isAppraised, function ($query) use ($isAppraised) {

                $query->where('is_appraised', $isAppraised);
            })

            ->when($createdAt, function ($query) use ($createdAt) {
                $query->whereBetween('created_at', $createdAt);
            })
            ->where('company_id',$companyId)
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));

        // 全部VIP
        $roles = Role::query()->select(['id', 'title'])->where('company_id',$companyId)->get();

        // 会员备注
        $userRemarks = UserRemark::query()
            ->whereIn('user_id', array_column($members->items(), 'id'))
            ->where('company_id',$companyId)
            ->select(['user_id', 'remark'])
            ->get()
            ->keyBy('user_id');

        return $this->successData([
            'data' => $members,
            'roles' => $roles,
            'user_remarks' => $userRemarks,
        ]);
    }

    /**
     * 会员所有的评价
     * @param Request $request
     * @return JsonResponse
     */
    public function appraise(Request $request)
    {
        $companyId =$this->loginCompanyId();
        $size = $request->input('size', 20);
        $userIds = UserRole::query()->where('company_id', $companyId)->pluck('user_id')->toArray();
        $appraises = Appraise::query()
            ->with(['user:id,avatar,nick_name'])
            ->where('company_id', $companyId)
            ->whereIn('user_id', $userIds)
            ->paginate($size);
        return $this->successData(compact('appraises'));

    }
    /**
     * @api {get} /api/v2/role/{id} VIP会员详情
     * @apiGroup VIP
     * @apiVersion v2.0.0
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     * @apiSuccess {Number} data.id VIPid
     * @apiSuccess {String} data.name VIP名
     * @apiSuccess {Number} data.charge 价格
     * @apiSuccess {Number} data.expire_days 有效天数
     * @apiSuccess {String[]} data.desc_rows 描述
     */
    public function detail($id)
    {
        $role = $this->roleService->get($id);
        $role = arr1_clear($role->toArray(), ApiV2Constant::MODEL_ROLE_FIELD);
        return $this->successData(compact('role'));
    }

    public function store(RoleRequest $request,Role $role)
    {
        $data = $request->filldata();
        $role->fill($data)->save();
        $role->privileges()->attach($data['privilege_ids']);
        return $this->success(__('插入会员记录成功'));
    }

    public function edit($id)
    {
        $role = $this->roleService->get($id);

        return $this->successData(compact('role'));
    }

    public function update(RoleRequest $request, $id)
    {
        $data =  $request->filldata();
        $role = Role::findOrFail($id);
        $role->fill($data)->save();
        $role->privileges()->sync($data['privilege_ids']);

        return $this->success();
    }

    public function delete($id)
    {
        if (User::query()->where('role_id', $id)->exists()) {
            return $this->error(__('当前VIP下存在用户无法删除'));
        }

        Role::destroy($id);

        return $this->success(__('删除会员成功'));
    }


    public  function     syncPrivilege(Request $request,$id){
        $ids = $request->input('ids',[]);
        $role  = Role::find($id);
        $role->privileges()->sync($ids);
        return $this->success(__('同步权限成功'));


  }
    public  function     deletePrivilege(Request $request,$id,$privilegeId){


        $role  = Role::find($id);
        $role->privileges()->detach($privilegeId);
        return $this->success(__('删除权限成功'));
    }
}
